import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth.js'
import { loginApi, getInfoApi, getAvatarInfo } from '@/api/user.js'
import { Promise } from 'core-js'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      setToken(payload)
      setTimeStamp(Date.now())
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async vuexLogin(ctx, data) {
      try {
        const { data: res } = await loginApi(data)
        ctx.commit('setToken', res.data)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async getUserInfo(ctx) {
      try {
        const { data: res } = await getInfoApi()
        const { data: result } = await getAvatarInfo(res.data.userId)
        const myInfo = { ...res.data, ...result.data }
        ctx.commit('setUserInfo', myInfo)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('removeUserInfo')
    }
  }
}

